<?php


namespace App\Repositories\Seller;


use App\Models\Goods;
use App\Models\GoodsSku;
use App\Repositories\BaseRepository;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class GoodsRepository extends BaseRepository
{

    /**
     * @return Model
     */
    public function model()
    {
        return new Goods();
    }

    /**
     * 创建商品
     * @param $data
     * @param $skus
     * @return mixed
     */
    public function create($data, $skus)
    {
        $max_price = 0;
        $min_price = 0;
        $stock = 0;
        foreach ($skus as &$sku) {
            $sku['thumb'] = $sku['thumb']??(string)($sku['thumb']);
            $sku['seller_id'] = $data['seller_id'];
            if ($sku['price'] > $max_price || $max_price == 0) {
                $max_price = $sku['price'];
            }
            if ($sku['price'] < $min_price || $min_price == 0) {
                $min_price = $sku['price'];
            }
            $stock += $sku['stock'];
        }
        $insertData = $data;
        $insertData['max_price'] = $max_price;
        $insertData['min_price'] = $min_price;
        $insertData['desc'] = $data['desc'] ?? '';
        $insertData['stock'] = $stock;
        return DB::transaction(function () use ($insertData, $skus) {
            $goods = $this->model()->create($insertData);
            if ($goods) {
                $skus = $goods->sku()->createMany($skus);
                if ($skus) {
                    return $goods;
                } else {
                    DB::rollBack();
                    return false;
                }
            } else {
                DB::rollBack();
                return false;
            }
        });
    }


    /**
     * 更新商品
     * @param Model $goods
     * @param $updateData
     * @return bool|Model|mixed
     */
    public function updateGoods(Model $goods, $updateData)
    {
        $sku_orginal = $goods->sku;
        $data = $updateData['goods'];
        if ($sku_orginal) {
            $delete_sku_id = $sku_orginal->pluck('id')->toArray();
        } else {
            $delete_sku_id = [];
        }
        $skus = $updateData['sku'];
        $update_sku = [];
        $add_sku = [];
        $max_price = 0;
        $min_price = 0;
        $stock = 0;
        foreach ($skus as $sku) {
            $sku['thumb'] = $sku['thumb']??(string)($sku['thumb']);
            if ($sku['id'] == 0) {
                $add_sku[] = [
                    'name' => $sku['name'],
                    'thumb' => $sku['thumb'],
                    'seller_id'=>$goods->seller_id,
                    'stock' => $sku['stock'],
                    'price' => $sku['price'],
                    'status' => $sku['status']
                ];
            } else {
                $key = array_search($sku['id'], $delete_sku_id);
                if ($key !== false) {
                    unset($delete_sku_id[$key]);
                }

                $update_sku[] = [
                    'id' => $sku['id'],
                    'name' => $sku['name'],
                    'thumb' => $sku['thumb'],
                    'stock' => $sku['stock'],
                    'price' => $sku['price'],
                    'status' => $sku['status']
                ];
            }
            $sku['seller_id'] = $goods->seller_id;
            if ($sku['price'] > $max_price || $max_price == 0) {
                $max_price = $sku['price'];
            }
            if ($sku['price'] < $min_price || $min_price == 0) {
                $min_price = $sku['price'];
            }
            $stock += $sku['stock'];
        }
        $data['stock'] = $stock;
        $data['max_price'] = $max_price;
        $data['min_price'] = $min_price;
        return DB::transaction(function () use ($goods, $data, $update_sku, $add_sku, $delete_sku_id) {
            //先编辑商品
            if ($this->_updateGoods($goods,$data,$update_sku,$add_sku,$delete_sku_id)){
                return true;
            }
            DB::rollBack();
            return false;
        });
    }

    /**
     * 更新商品（私有方法）
     * @param $goods
     * @param $data
     * @param $update_sku
     * @param $add_sku
     * @param $delete_sku_id
     * @return bool
     */
    private function _updateGoods($goods, $data, $update_sku, $add_sku, $delete_sku_id){
        if ($goods->update($data)) {
            //删除没有的sku
            $delete_count = GoodsSku::destroy($delete_sku_id);
            if ($delete_count != count($delete_sku_id)) {
                return false;
            }
            //添加新的
            if (!$goods->sku()->createMany($add_sku)) {
                return false;
            }
            //更新旧的
            foreach ($update_sku as $item) {
                if (!GoodsSku::where(['id' => $item['id']])->update([
                    'name' => $item['name'],
                    'thumb' => $item['thumb'],
                    'stock' => $item['stock'],
                    'price' => $item['price']*100,
                    'status' => $item['status']
                ])) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }
}